package cn.edu.scnu.comment.service;

import cn.edu.scnu.comment.mapper.CommentMapper;
import cn.edu.scnu.pojo.Comment;
import cn.edu.scnu.vo.CommentVO;
import cn.edu.scnu.vo.SysResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Lazy
    @Resource(type = RestTemplate.class)
    private RestTemplate restTemplate;

    public void saveComment(Comment comment) {
        comment.setId(UUID.randomUUID().toString());
        commentMapper.saveComment(comment);
    }

    public List<CommentVO> getCommentByMatchId(String matchId) {
        List<CommentVO> data = commentMapper.getCommentByMatchId(matchId);
        if (data.isEmpty()) {
            return data;
        }
        for (CommentVO commentVO : data) {
            if (StringUtils.isNotEmpty(commentVO.getFromName())) {
                SysResult result = restTemplate.getForObject("http://userService/users/" +
                        commentVO.getFromName() + "/info", SysResult.class);
                if (result.getStatus() == 200) {
                    Map<String, String> map = (Map<String, String>) result.getData();
                    commentVO.setFromNick(map.get("nickname"));
                    commentVO.setFromImgurl(map.get("imgurl"));
                }
            }
            if (StringUtils.isNotEmpty(commentVO.getToName())) {
                SysResult result = restTemplate.getForObject("http://userService/users/" +
                        commentVO.getToName() + "/info", SysResult.class);
                if (result.getStatus() == 200) {
                    Map<String, String> map = (Map<String, String>) result.getData();
                    commentVO.setToNick(map.get("nickname"));
                    commentVO.setToImgurl(map.get("imgurl"));
                }
            }
            // TODO 多级评论查询
        }
        return data;
    }

    public void likeComment(String commentId) {
        commentMapper.likeComment(commentId);
    }

    public Integer delCommentById(String username, String commentId) {
        // TODO 多级评论的删除
        return commentMapper.delCommentById(username, commentId);
    }

    public void delCommentMatchId(String matchId) {
        commentMapper.delCommentByMatchId(matchId);
    }
}
